/*
 * @Description: 请假管理
 * @Author: DHL
 * @Date: 2022-12-23 13:52:43
 * @LastEditors: DHL
 * @LastEditTime: 2023-06-29 11:11:26
 */

import { defineComponent, computed, reactive, ref } from 'vue'
import { log } from '../../../utils/logUtils'
import { ElMessage } from 'element-plus'
import { cloneDeep, assign } from 'lodash-es'
import { LeaveModel } from '@/api/oa/model/leaveModel'
import { isEmpty } from '@/utils/isUtils'
import { apiLeaveGetById, apiLeaveSave, apiLeaveUpdateById } from '@/api/oa/leave'

export default defineComponent({
  name: 'LeaveForm',
  emits: ['refreshTableData'],
  setup(props, { emit, expose }) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////
    const dbFormRef = ref()
    const loading = ref(true)

    const formDisabled = ref(false)

    /**
     * 表单操作标记
     */
    const action = ref('add')

    /**
     * 显示弹框
     */
    const visible = ref(false)

    /**
     * 标题
     */
    const title = computed(() => {
      let rtn = ''
      switch (action.value) {
        case 'add':
          rtn = '新增'
          break
        case 'edit':
          rtn = '编辑'
          break
        default:
          rtn = '查看'
          break
      }
      return rtn
    })

    /**
     * 公共
     */
    const state = reactive({})

    //////////////////////////////////////////////////
    // 表单
    //////////////////////////////////////////////////

    const defaultForm = {
      id: '', // 主键
      name: '', // 名称
      code: '', // 编码
      type: '', // 类型
      beginTime: '', // 开始时间
      endTime: '', // 结束时间
      duration: 0, // 时长
      because: '' // 事由
    }

    let dbForm = reactive<LeaveModel>(cloneDeep(defaultForm))

    //////////////////////////////////////////////////
    // 表单验证规则
    //////////////////////////////////////////////////

    /**
     * 表单验证规则
     */
    const rules = reactive({
      name: [
        {
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        },
        {
          max: 200,
          message: '最多可输入200个字符',
          trigger: 'blur'
        }
      ],
      code: [
        {
          required: true,
          message: '请输入编码',
          trigger: 'blur'
        },
        {
          max: 50,
          message: '最多可输入50个字符',
          trigger: 'blur'
        }
      ],
      type: [
        {
          required: true,
          message: '请选择类型',
          trigger: 'blur'
        },
        {
          max: 10,
          message: '最多可输入10个字符',
          trigger: 'blur'
        }
      ],
      beginTime: [
        {
          required: true,
          message: '请选择开始时间',
          trigger: 'blur'
        }
      ],
      endTime: [
        {
          required: true,
          message: '请选择结束时间',
          trigger: 'blur'
        }
      ],
      duration: [
        {
          required: true,
          message: '请输入时长',
          trigger: 'blur'
        }
      ],
      because: [
        {
          required: true,
          message: '请输入事由',
          trigger: 'blur'
        },
        {
          max: 1000,
          message: '最多可输入1000个字符',
          trigger: 'blur'
        }
      ]
    })

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 打开弹框
     */
    function handleOpen(actionParam: string, rowParam?: LeaveModel) {
      visible.value = true
      loading.value = false
      action.value = actionParam
      if (['edit', 'view', 'approval'].indexOf(actionParam) > -1 && rowParam) {
        dbForm.id = rowParam?.id
        handleSearchById(rowParam?.id)
      }
    }

    /**
     * 关闭弹框
     */
    function handleClose() {
      visible.value = false
      assign(dbForm, cloneDeep(defaultForm))
      emit('refreshTableData')
    }

    /**
     * 根据主键查询详情
     * @param id 主键
     */
    function handleSearchById(id = '') {
      if (isEmpty(id)) {
        return
      }
      loading.value = true
      apiLeaveGetById(id)
        .then((result) => {
          if (result?.success) {
            assign(dbForm, result.data)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 提交表单
     */
    function handleSubmit(processStartParams: any) {
      dbFormRef.value.validate((valid: boolean) => {
        if (valid) {
          if (action.value === 'add') {
            addFun(processStartParams)
          } else {
            editFun(processStartParams)
          }
        } else {
          log.warn('请假管理', '表单校验失败')
        }
      })
    }

    /**
     * 新增
     * @param isContinue 是否新增并继续
     */
    function addFun(processStartParams: any) {
      loading.value = true
      apiLeaveSave({ ...dbForm, ...processStartParams })
        .then((result) => {
          if (result?.success) {
            handleReset()
            ElMessage.success(result.message)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 编辑
     * @returns
     */
    function editFun(processStartParams: any) {
      loading.value = true
      apiLeaveUpdateById({ ...dbForm, ...processStartParams })
        .then((result) => {
          if (result?.success) {
            handleReset()
            ElMessage.success(result.message)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 重置表单
     * @param isClosed 是否关闭弹框
     */
    function handleReset() {
      assign(dbForm, cloneDeep(defaultForm))
      visible.value = false
    }

    /**
     * 禁用表单
     */
    function handleDisabled(val: boolean) {
      formDisabled.value = val
    }

    /**
     * 加载动画
     * @param val
     */
    function handleLoading(val: boolean) {
      loading.value = val
    }

    /**
     * 暴露函数
     */
    expose({ handleOpen })

    return {
      loading,
      formDisabled,
      visible,
      action,
      title,
      state,
      dbFormRef,
      dbForm,
      rules,
      handleOpen,
      handleClose,
      handleSubmit,
      handleReset,
      handleDisabled,
      handleLoading
    }
  }
})
